import React, { useState, useEffect } from 'react';

import './content.less';

import {
  Form,
  Input,
  Button,
  DatePicker,
  Table,
  Tag,
  Space,
  Pagination,
  message,
} from 'antd';
const { RangePicker } = DatePicker;

import { formTableApi, activityDeleteIdApi } from '@/api/createActivity.js';
import { history } from 'umi';
let allData = [];
let bus = {
  //  事件总线
  list: [],
  subscribe(callback) {
    this.list.push(callback);
  },
  publish(value) {
    this.list.forEach((f) => {
      f && f(value);
    });
  },
};
export default function (props) {
  const [state, setState] = useState();
  const [form] = Form.useForm();
  const [activityName, setActivityName] = useState(''); // 输入框输入的值
  const [queryStartDate, setQueryStartDate] = useState(''); // 日期选择器  开始时间
  const [queryEndDate, setQueryEndDate] = useState(''); // 日期选择器  结束时间

  const [page, setPage] = useState(1); // 当前页面 为 1
  const [pageSize, setPageSize] = useState(10); // 每条页数
  const [total, setTatal] = useState(0); //  总页数
  const [tableData, setTableData] = useState([]); // tabel数据

  useEffect(() => {
    //  监听到了以后 点击 删除 按钮
    bus.subscribe(({ id, activityBasicId }) => {
      activityDeleteIdApi({ activityBasicIds: [activityBasicId] })
        .then((res) => {
          if (res.data.code === 200) {
            let a = JSON.parse(JSON.stringify(tableData));
            let b = a.filter((f) => f.id !== id);
            setTableData(b);
            message.success(res.data.message);
          } else {
            message.error(res.data.message);
          }
        })
        .catch((err) => console.log('err:', err));
    });
  });

  useEffect(() => {
    tableDataFn(pageSize, page); // 初始化
  }, []);
  useEffect(() => {
    //   console.log("传过来的 id ", props.selectTags)
    if (props.selectTags[0] == 11) {
      // 说明就是 草稿  草稿 我就传了一个 [1]
      setPage(1);
      tableDataFn(
        pageSize,
        1,
        activityName,
        queryStartDate,
        queryEndDate,
        null,
        1,
      );
    } else if (props.selectTags[0] == 100) {
      setPage(1);
      tableDataFn(pageSize, 1, activityName, queryStartDate, queryEndDate);
    } else {
      setPage(1);
      tableDataFn(
        pageSize,
        1,
        activityName,
        queryStartDate,
        queryEndDate,
        props.selectTags,
      );
    }
  }, [props.selectTags]);

  const tableDataFn = async (
    pageSize = 10,
    page = 1,
    activityName,
    queryStartDate,
    queryEndDate,
    activityStatus,
    isDraft,
  ) => {
    await formTableApi({
      page, // 当前 页数
      pageSize, // 每条页数
      activityName, // 活动名称
      queryStartDate, // 开始时间
      queryEndDate, // 结束时间
      activityStatus, //  活动状态 1-待审核  2-进行中   3-未开始  4-已驳回  5-已结束 [1] 传的格式
      isDraft, //  是否 草稿   1 是  0  否
    })
      .then((res) => {
        // console.log("table数据:", res.data.data.rows)
        if (res.data.code == 200) {
          setTatal(res.data.data.total);
          let arr = res.data.data.rows.map((m) => ({
            ...m,
            key: m.id,
            activityTime: m.startDate + '-' + m.endDate,
            selectTags: props.selectTags[0],
          }));
          // console.log("table数据:  ", arr)
          allData = arr;
          setTableData(arr);
        } else if (res.data.code === 999) {
          message.error(res.data.message);
        }
      })
      .catch((err) => console.log('err:', err));
  };

  const handleDelete = (id) => {
    console.log('删除的 回调', id);
  };

  const handleInput = (e) => {
    // input 框输入后 触发的回调
    // console.log("e:", e.target.value)
    setActivityName(e.target.value);
  };
  const handleTime = (e, time) => {
    // 选择日期
    // console.log("ee", e, time)
    // setActivityTime(time)  // time 是一个 数组
    setQueryStartDate(time[0]);
    setQueryEndDate(time[1]);
  };

  const handleSearch = () => {
    // 搜索 按钮
    // console.log('input框:', activityName);
    // console.log('开始:', queryStartDate, "结束：",  queryEndDate);
    if (props.selectTags[0] == 100) {
      setPage(1);
      tableDataFn(pageSize, 1, activityName, queryStartDate, queryEndDate);
    } else if (props.selectTags[0] == 11) {
      tableDataFn(
        pageSize,
        1,
        activityName,
        queryStartDate,
        queryEndDate,
        null,
        1,
      );
    } else {
      setPage(1);
      tableDataFn(
        pageSize,
        1,
        activityName,
        queryStartDate,
        queryEndDate,
        props.selectTags,
      );
    }
    // console.log("data", tableData)
  };

  const handleReset = () => {
    //  重置按钮
    form.resetFields(); // 重置
    setActivityName(''); // 活动名称
    setQueryStartDate(''); // 开始时间
    setQueryEndDate(''); // 结束时间
    tableDataFn(); // 重置
    setPage(1);
  };

  const handleCreateActivity = () => {
    // 创建活动
    // history.push({
    //     pathname: '/home/createActivity/addActivity',
    // })
    history.push('/home/createActivity/addActivity');
  };

  const handlePagination = (page_1, pageSize) => {
    //  分页
    console.log('分页', page_1, pageSize);
    setPage(page_1);
    if (props.selectTags[0] == 100) {
      tableDataFn(pageSize, page_1, activityName, queryStartDate, queryEndDate);
    } else if (props.selectTags[0] == 11) {
      tableDataFn(
        pageSize,
        page_1,
        activityName,
        queryStartDate,
        queryEndDate,
        null,
        1,
      );
    } else {
      tableDataFn(
        pageSize,
        page_1,
        activityName,
        queryStartDate,
        queryEndDate,
        props.selectTags,
      );
    }
  };
  //   const handlePageSize = (current, size) => {  // pageSize 变化的回调
  //     console.log("pageSize 变化的回调",current, size )
  //     if(props.selectTags[0] == 100) {
  //         tableDataFn(current, size, activityName, queryStartDate, queryEndDate)

  //     } else {
  //         tableDataFn(current, size, activityName, queryStartDate, queryEndDate, props.selectTags)
  //     }
  //   }
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'activityName',
      key: 'activityName',
      //   render: text => <a>{text}</a>,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
    },
    {
      title: '活动时间',
      dataIndex: 'activityTime',
      key: 'activityTime',
    },
    {
      title: '状态',
      key: 'activityStatus',
      dataIndex: 'activityStatus',
      render: (_, { activityStatus, selectTags, isDraft }) => {
        // console.log(activityStatus,isDraft, selectTags);
        // let str = ''     //  方式一
        // if (isDraft) {
        //     str = '草稿'
        // } else {
        //     switch (activityStatus) {
        //         case 1:
        //             str = '待审核'
        //             break;
        //         case 2:
        //             str = '进行中'
        //             break;
        //         case 3:
        //             str = '未开始'
        //             break;
        //         case 4:
        //             str = '已驳回'
        //             break;
        //         case 5:
        //             str = '已结束'
        //             break;

        //         default:
        //             break;
        //     }
        // }
        return (
          <>
            <div style={{ color: '#36a898' }}>
              {' '}
              {
                // str  //  方式 一
                isDraft && selectTags == 11
                  ? '草稿' //  方式二
                  : activityStatus == 1 && selectTags != 11
                  ? '待审核'
                  : activityStatus == 2 && selectTags != 11
                  ? '进行中'
                  : activityStatus == 3 && selectTags != 11
                  ? '未开始'
                  : activityStatus == 4 && selectTags != 11
                  ? '已驳回'
                  : activityStatus == 5 && selectTags != 11
                  ? '已结束'
                  : null
              }{' '}
            </div>
          </>
        );
      },
    },
    {
      title: '操作',
      // key: 'id',
      dataIndex: 'activityStatus',
      key: 'activityStatus',
      render: (
        _,
        { id, activityStatus, selectTags, isDraft, activityBasicId },
        index,
      ) => {
        // console.log('111'.activityStatus, '---', id, selectTags, isDraft, index)
        // console.log('111'.activityStatus, id, selectTags, isDraft, index)
        // console.log('222'.record)
        // console.log('333'.index)
        return (
          <div style={{ display: 'flex' }}>
            {selectTags == 11 && (
              <div
                style={{
                  marginRight: '5px',
                  cursor: 'pointer',
                  color: '#4ea3ff',
                }}
                onClick={() => {
                  // console.log("id",id, "activityBasicId", activityBasicId)
                  history.push({
                    pathname: '/home/createActivity/addActivity',
                    query: {
                      activityBasicId,
                    },
                  });
                }}
              >
                编辑
              </div>
            )}
            <div
              style={{
                color: '#4ea3ff',
                cursor: 'pointer',
                marginRight: '5px',
              }}
              onClick={() => {
                history.push({
                  pathname: '/home/createActivity/activityDetail',
                  query: {
                    activityBasicId,
                  },
                });
              }}
            >
              详情
            </div>
            <div
              style={{
                cursor: 'pointer',
                color: '#4ea3ff',
              }}
              onClick={() => {
                // bus.publish({id, activityBasicId})  //  删除 这种方式 不行， 会触发 多次

                activityDeleteIdApi({ activityBasicIds: [activityBasicId] })
                  .then((res) => {
                    if (res.data.code === 200) {
                      let a = JSON.parse(JSON.stringify(tableData));
                      let b = a.filter((f) => f.id !== id);
                      setTableData(b);
                      message.success(res.data.message);
                    } else {
                      message.error(res.data.message);
                    }
                  })
                  .catch((err) => console.log('err:', err));
              }}
            >
              删除
            </div>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      {/* input 模块 */}
      <div className="activity_input">
        <Form
          form={form}
          name="basic"
          initialValues={{ activityName: '', createTime: '' }}
          // onFinish={handleSearch}
          // onFinishFailed={handleReset}
          autoComplete="off"
          className="activity_form"
        >
          <div className="activity_form_input">
            <Form.Item
              label="活动名称"
              name="activityName"
              style={{
                marginRight: '25px',
              }}
            >
              <Input placeholder="请输入" onChange={(e) => handleInput(e)} />
            </Form.Item>

            <Form.Item label="创建时间" name="createTime">
              <RangePicker onChange={handleTime} showTime />
            </Form.Item>
          </div>
          <div style={{ whiteSpace: 'nowrap' }}>
            <Button
              onClick={handleSearch}
              style={{
                background: '#1a267b',
                color: '#fff',
                borderRadius: '6px',
                marginRight: '5px',
              }}
            >
              {' '}
              搜索{' '}
            </Button>
            <Button
              onClick={handleReset}
              style={{
                borderRadius: '6px',
              }}
            >
              {' '}
              重置{' '}
            </Button>
          </div>
        </Form>

        <Button
          style={{
            background: '#1a267b',
            color: '#fff',
            borderRadius: '6px',
            marginRight: '5px',
            marginBottom: '15px',
          }}
          onClick={handleCreateActivity}
        >
          {' '}
          + 创建活动{' '}
        </Button>
      </div>

      {/* table 表格 模块 */}
      <div>
        <Table pagination={false} columns={columns} dataSource={tableData} />
        <Pagination
          showQuickJumper
          total={total}
          onChange={handlePagination}
          // onShowSizeChange={handlePageSize}
          showTotal={() => {
            return `共${total}条`;
          }}
          // pageSize={pageSize}
          current={page}
          style={{
            textAlign: 'right',
            marginTop: '15px',
          }}
        />
      </div>
    </div>
  );
}
